package com.res.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.res.entity.Department;
import com.res.entity.Student;
import com.res.entity.Teacher;
import com.res.repository.DepartmentRepository;
import com.res.repository.TeacherRepository;
import com.res.service.TeacherService;
import com.res.util.FenyeUtil;

@Service
public class TeacherServiceImpl implements TeacherService {

	@Autowired
	private TeacherRepository tff;
	@Autowired
	private DepartmentRepository dff;
	@Override
	public FenyeUtil<Teacher> GetTeachByPage(Teacher t,Integer did, Pageable page) {
		
		 //配置pageable 因为查询去掉复制id为1的数据
		    Page<Teacher> ts = tff.findAll(get(t,did),page);
		    FenyeUtil<Teacher> tt = new FenyeUtil<Teacher>();
		    tt.setData(ts.getContent());
		    tt.setCount((int)ts.getTotalElements()-1);
		    List<Teacher> ls = new ArrayList<Teacher>();
			for(int i=0;i<tt.getData().size();i++) {
				if(tt.getData().get(i).getTid()==1) {
					
				}else {
					ls.add(tt.getData().get(i));
				}
			}
			tt.setData(ls);
			
		return tt;
	}

	private Specification<Teacher> get(Teacher t,Integer did) {
		// TODO Auto-generated method stub
		return new Specification<Teacher>() {
			
			@Override
			public Predicate toPredicate(Root<Teacher> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				// TODO Auto-generated method stub
				Predicate p = criteriaBuilder.conjunction();
				List<Expression<Boolean>> ep=p.getExpressions();
				if(t.getTname()!=null&&t.getTname()!="") {
					ep.add(criteriaBuilder.like(root.get("tname"), "%"+t.getTname()+"%"));
				}
				if(did!=null) {
					ep.add(criteriaBuilder.equal(root.get("department").get("did"), did));
				}
				return p;
			}
		};
	}

	@Override
	public Integer AddAndUpd(Teacher t) {
		// TODO Auto-generated method stub
		try {
			tff.saveAndFlush(t);
			return 1;
		} catch (Exception e) {
			// TODO: handle exception
			return 0;
		}
	}

	@Override
	public Integer Del(Integer tid) {
		// TODO Auto-generated method stub
		try {
			tff.deleteById(tid);
			return 1;
		} catch (Exception e) {
			// TODO: handle exception
			return 0;
		}
	}
	public List<Department> GetAll(){
		return dff.findAll();
	}

}
